<template>
  <div class="container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-row type="flex" align="middle" justify="end" style="height: 60px">
          <el-button type="primary" size="small" @click="showRoleDialog = true">新增角色</el-button>
        </el-row>
        <el-table border :data="list">
          <el-table-column align="center" type="index" label="序号" width="120" :index="indexFn" />
          <el-table-column align="center" label="角色" width="240">
            <template v-slot="{ row }">
              <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="state" label="状态" width="240">
            <template v-slot="{row}">
              <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
              <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="description" label="描述">
            <template v-slot="{ row }">
              <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" type="textarea" />
              <span v-else>{{ row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template v-slot="{row}">
              <template v-if="row.isEdit">
                <el-button type="primary" size="mini" @click="btnEditOK(row)">确定</el-button>
                <el-button size="mini" @click="row.isEdit = false">取消</el-button>
              </template>
              <template v-else>
                <el-button size="small" type="text" @click="btnPermission(row.id)">分配权限</el-button>
                <el-button size="small" type="text" @click="btnEditRow(row)">编辑</el-button>
                <el-button size="small" type="text" @click="deleteRole(row.id)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置分页组件 -->
        <el-row type="flex" align="middle" justify="center" style="height: 60px">
          <el-pagination :page-sizes="[2, 4, 6, 8, 10]" layout="total, sizes, prev, pager, next, jumper" :page-size="query.pagesize" :current-page="query.page" :total="total" @current-change="changeCurrent" @size-change="changeSize" />
        </el-row>
      </el-card>
      <el-dialog width="500px" title="新增角色" :visible.sync="showRoleDialog" @close="cancelRoleDialog">
        <el-form ref="roleForm" label-width="120px" :model="roleForm" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用" prop="state">
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
                <el-button size="mini" @click="cancelRoleDialog">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog :visible="showPermissionDialog" title="分配权限" @close="cancelPermDialog">
        <!-- 放置权限数据 -->
        <el-tree ref="permTree" check-strictly node-key="id" :data="permissionData" :props="{ label: 'name' }" show-checkbox default-expand-all :default-checked-keys="permIds" />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
            <el-button size="mini" @click="cancelPermDialog">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permission'
import { getRoleDetail, assignPerm } from '@/api/role'
import { getRoleList, deleteRole, addRole, updateRole } from '@/api/role'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      query: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      loading: false,
      showRoleDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 0 关闭
      },
      rules: {
        name: [{
          required: true,
          message: '角色名称不能为空',
          trigger: 'blur'
        }],
        description: [{
          required: true,
          message: '角色描述不能为空',
          trigger: 'blur'
        }]
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const {
        rows,
        total
      } = await getRoleList(this.query)
      this.list = rows
      this.total = total
      this.loading = false
      // this.list.forEach(item => (item.isEdit = false))
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    changeCurrent(page) {
      this.query.page = page
      this.getRoleList()
    },
    changeSize(size) {
      // 每页的条数变化后，当前页不一定就是当前页了
      this.query.page = 1
      this.query.pagesize = size
      this.getRoleList()
    },
    indexFn(index) {
    // index + 1 当前页的序号，默认就是这个，展示是 0、1、2 这样
    // （页码 - 1） * 每页展示多少条
      return index + 1 + (this.query.page - 1) * this.query.pagesize
    },
    async deleteRole(id) {
      try {
        // 只有点击了确定才能进入到下方
        await this.$confirm('确认删除该角色吗')
        // 调用删除接口
        await deleteRole(id)
        if (this.list.length === 1 && this.query.page > 1) {
          this.query.page--
        }
        // 重新加载数据
        this.getRoleList()
        // 提示
        this.$message.success('删除角色成功')
      } catch (error) {
        console.log(error)
      }
    },
    async btnOK() {
      try {
        // 只有校验通过的情况下，才会执行 await 的下方内容
        await this.$refs.roleForm.validate()
        // 新增业务
        await addRole(this.roleForm)
        this.getRoleList()
        this.$message.success('操作成功')
        this.cancelRoleDialog()
      } catch (error) {
        console.log(error)
      }
    },
    cancelRoleDialog() {
      this.showRoleDialog = false
      this.$refs.roleForm.resetFields()
    },
    btnEditRow(row) {
      row.isEdit = true
      // #mark
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async btnEditOK(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({
          ...row.editRow,
          id: row.id
        })
        this.$message.success('更新角色成功')
        // row.name = row.editRow.name
        // row.state = row.editRow.state
        // row.description = row.editRow.description
        // row.isEdit = false
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async btnPermission(id) {
      this.currentRoleId = id
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    },
    cancelPermDialog() {
      this.showPermissionDialog = false
      this.permIds = []
    }
  }
}
</script>
